package com.tuozixuan;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.logging.Log;

import com.github.houbb.opencc4j.util.ZhConverterUtil;

public class FileProcessor {

	private File file;

	private PluginConfig pluginConfig;
	
	private Log log;

	public FileProcessor(File file, PluginConfig pluginConfig, Log log) {
		this.file = file;
		this.pluginConfig = pluginConfig;
		this.log = log;
	}

	public Optional<FileResult> execute() {
		
		int lineNo = 0;
		List<LineResult> lineResultList = new ArrayList<>();
		List<String> lines;
		try {
			lines = FileUtils.readLines(file, "UTF-8");
		} catch (IOException e) {
			log.error(e);
			throw new RuntimeException("文件信息讀取失敗", e);
		}
		
		for (String line : lines) {
			
			lineNo ++;
			if (StringUtils.isBlank(line) || !this.filterLine(line)) {
				continue;
			}

			String traditionalLine = ZhConverterUtil.toTraditional(line);
			if (!traditionalLine.equals(line)) {
				LineResult lineResult = new LineResult();
				lineResult.setSourceLine(line.trim());
				lineResult.setTargetLine(traditionalLine.trim());
				lineResult.setLineNo(lineNo);
				lineResultList.add(lineResult);
			}
		}
		
		FileResult fileResult = null;
		if (lineResultList.size() > 0) {
			fileResult = new FileResult();
			fileResult.setFile(file);
			fileResult.setLineResultList(lineResultList);
			log.info(fileResult.toString());
		}
		
		return Optional.ofNullable(fileResult);
	}
	
	private boolean filterLine(String line) {
		for (String excludeLinePattern : pluginConfig.getExcludeLinePatterns()) {
			if (line.matches(excludeLinePattern)) {
				return false;
			}
		}
		return true;
	}

}
